# -*- coding: utf-8 -*-
import logging
import os
import sys
import time
from datetime import datetime, timedelta

import requests

# add up one level dir into sys path

sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(
    os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))))
os.environ['DJANGO_SETTINGS_MODULE'] = 'base.settings'

from common.lottery.cyclical.tc_pls.db.activity import fullfill_result
from common.lottery import LOTTERY_TYPE, PROXY_URL, OPENCAI_LOTTERY_TYPES
from common.timer import TIMER_EVENT_TYPE, TimerEvent
from common.utils import tz
from common.lottery.handler import crawl_from_opencai


def _get_default_date():
    date = tz.utc_to_local(datetime.utcnow())
    # 如果是第二天刚开始的时候，需要去爬前一天最后几期的结果
    if date.hour == 0 and date.minute < 3:
        date -= timedelta(days=1)
    return date


def crawl_from_168(date=None):
    calc_date = date or _get_default_date()
    url = 'http://api.1680210.com/QuanGuoCai/getLotteryInfoList.do?date=%s&lotCode=10043' % calc_date.strftime(
        '%Y-%m-%d')
    try:
        response = requests.post(url, proxies={'http': PROXY_URL}, timeout=5)
    except Exception as e:
        raise e
    if response.status_code != 200:
        raise RuntimeError('request error')
    _parse_and_fill_168(response.json(), url)


def _parse_and_fill_168(data, refer):
    if data['errorCode'] == 0:
        nodes = data['result']['data']
        for node in nodes:
            phase = node['preDrawIssue']  # 期號
            number = node['preDrawCode']  # 開獎結果
            activity = fullfill_result(phase, number, refer)

            if activity:
                TimerEvent.submit(TIMER_EVENT_TYPE.CALC_STATS, {  # 走勢圖
                    'number': number, 'term': phase,
                    'activity_type': LOTTERY_TYPE.TC_PLS}, tz.now_ts()
                                  )
                TimerEvent.submit(TIMER_EVENT_TYPE.ACTIVITY_ANNOUNCE, {  # 中獎結算
                    'number': number, 'term': phase,
                    'activity_type': LOTTERY_TYPE.TC_PLS}, tz.now_ts())


def crawl_from_official_now():
    url = 'http://www.lottery.gov.cn/api/lottery_index_kj.jspx'
    try:
        response = requests.get(url, proxies={'http': PROXY_URL}, timeout=10)
    except Exception as e:
        raise e
    if response.status_code != 200:
        raise RuntimeError('request error')

    data = response.json()

    phase = data[0]['pls']['term']  # 期號, 20xx 年
    number = ','.join(data[0]['pls']['numberCode'])  # 開獎結果

    activity = fullfill_result(phase, number, url)
    if activity:
        TimerEvent.submit(TIMER_EVENT_TYPE.CALC_STATS, {
            'number': number, 'term': phase,
            'activity_type': LOTTERY_TYPE.TC_PLS}, tz.now_ts())
        TimerEvent.submit(TIMER_EVENT_TYPE.ACTIVITY_ANNOUNCE, {
            'number': number, 'term': phase,
            'activity_type': LOTTERY_TYPE.TC_PLS}, tz.now_ts())


def main(d):
    while True:
        try:
            crawl_from_opencai(LOTTERY_TYPE.TC_PLS)
        except Exception as e:
            logging.exception(u'%s error: %s' % (OPENCAI_LOTTERY_TYPES.get(LOTTERY_TYPE.TC_PLS), e))
        if d:
            break
        time.sleep(60)


if __name__ == '__main__':
    date = sys.argv[1] if len(sys.argv) > 1 else None
    main(date)
